package net.pm.common.toolkit;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.pm.common.toolkit.date.DateUtils;

import org.springframework.web.context.ContextLoader;

/**
 * PM工具类,(工具类全为静态方法)声明为抽象以达到不可new　实例化的效果
 * @author shizeyuan
 *
 */
public abstract class PMTool {
	/**
	 * 获取Spting上下文bean对象
	 * @return
	 */
	public static <T> T obtainSpringBean(String beanname, Class<T> clazz){
		return ContextLoader.getCurrentWebApplicationContext().getBean(beanname, clazz);
	}
	

	/**
	 * 清空session
	 * @param session
	 */
	public static void clearSession(HttpSession session) {
		if (session == null)
			return;
		final Enumeration<String> em = session.getAttributeNames();
		while (em.hasMoreElements()){
			final String key = em.nextElement();
			session.removeAttribute(key);
		}
	}
	
	/**
	 * 对象是否为空
	 * @param obj
	 * @return
	 */
	public static Boolean isEmpty(Object obj){
		if(obj == null)
			return true;
		return false;
	}
	
	/**
	 * 对象是否不为空
	 * @param obj
	 * @return
	 */
	public static Boolean isNotEmpty(Object obj){
		return !isEmpty(obj);
	}
	
	
	/**生成订单编号
	 * @return
	 */
	public static final String generateUniqueno(String prefix) {
		final StringBuilder sb = new StringBuilder();
		sb.append(prefix);
		final char[] tempnowtimestampchars = DateUtils.obtainCurrentStrdate(DateUtils.FORMAT_FULL).substring(2).toCharArray();
		for (char c : tempnowtimestampchars) {
			if (c == '-' || c == ' ' || c == ':' || c == '.')
				continue;
			sb.append(c);
		}
		final int len = 18 - sb.length();
		int i = 1;
		for (; i <= len; i++) {
			sb.append(String.valueOf(Math.random()*100).charAt(0));
		}
		return sb.toString();
	}
	
	/**
	 * 是否包含,拥有该权限
	 * 
	 * @return
	 */
	public static boolean isHasPower(String code, List<String> powers) {
		for (String power : powers) {
			if (power.equals(code)) {
				return true;
			}
		}
		return false;
	}
	
	
}
